// pages/erp/erp.js
const app = getApp();
import request from "../../utils/request";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    productStatusMap: {},
    cartCount: 0,
    commodityNumber: 0,
    productList: [],
    result: [],
    priceNumber: null,
    allPrice: "0",
    allChecked: true,
    addShow: false,
    addList: {},
    alreadyList: {},
    tradeOrder: "",
    checkbox: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},
  async getOrderList() {
    const useID = wx.getStorageSync("userId");
    const res = await request({
      url:
        app.globalData.baseURL +
        `/app-api/package/cart/page?pageNo=${1}&pageSize=${50}`,
      method: "GET",
      userId: useID,
    });
    const list = res.data.list;
    let datalist = list.map((item) => {
      item.showPrice = (item.showPrice / 100).toFixed(2);
      return item;
    });
    wx.setStorageSync("count", Number(list.length));
    this.setData({
      productList: datalist,
      cartCount: list.length,
    });
  },
  async onClose(event) {
    const { position, instance } = event.detail;
    instance.close();
    let id = event.currentTarget.dataset.item.id;
    let list = this.data.productList;
    const cartId = event.currentTarget.dataset.item.id;
    wx.showModal({
      title: "提示",
      content: "您确定要删除该商品吗",
      success: (res) => {
        if (res.confirm) {
          // 用户点击确定，执行删除操作
          const filteredList = list.filter((item) => item.id !== id);
          this.setData({
            productList: filteredList,
          });
          this.deleteMsg(cartId);
        } else if (res.cancel) {
          // 用户点击取消，不执行任何操作
        }
      },
    });
  },
  async deleteMsg(cartId) {
    const num = await request({
      url: app.globalData.baseURL + `/app-api/package/cart/delete?id=${cartId}`,
      method: "DELETE",
    });
    if (num.code == 0) {
      wx.showToast({
        title: "删除商品成功",
        icon: "success",
      });
      const count = wx.getStorageSync("count");
      const cart = count - 1;
      wx.setStorageSync("count", cart);
      this.setData({
        cartCount: cart,
      });
    } else {
      wx.showToast({
        title: num.msg,
        icon: "none",
      });
    }
  },
  // 商品复选框变化时的函数
  onChange: function (event) {
    if (event.detail !== []) {
      this.setData({
        tradeOrder: event.currentTarget.dataset.item.cartId,
      });
    }
    const id = event.currentTarget.dataset.item.itemId;
    const checkedIds = event.detail; // 获取所有选中的商品 id 的数组
    this.setData({
      result: checkedIds,
    });
    // 计算总价
    this.calculateTotalPrice(checkedIds);
  },
  calculateTotalPrice: function (checkedIds) {
    const total = checkedIds.reduce((sum, id) => {
      const product = this.data.productList.find((item) => item.id == id);
      if (product.children.length !== 0) {
        const functionPrice = product.children.reduce(
          (accumulator, current) => {
            return accumulator + current.showPrice;
          },
          0
        );
        const price =
          sum + (product ? Number(product.showPrice) : 0) + functionPrice / 100;
        return price * product.years;
      } else {
        return (
          (sum + (product ? Number(product.showPrice) : 0)) * product.years
        );
      }
    }, 0); // 初始值设置为 0
    this.getOrderList();
    this.setData({
      allPrice: total,
    });
  },

  gocategory() {
    wx.switchTab({
      url: "../category/category",
    });
  },

  goback() {
    wx.navigateBack({
      delta: 1,
    });
  },
  async goPay() {
    if (this.data.tradeOrder !== "") {
      const res = await request({
        url: app.globalData.baseURL + "/app-api/package/trade-order/create",
        method: "POST",
        data: {
          cartNo: this.data.tradeOrder,
          type: 1,
          terminal: 10,
        },
      });
      if (res.code == 0) {
        const num = await request({
          url:
            app.globalData.baseURL +
            `/app-api/package/trade-order/get?id=${res.data.id}`,
          method: "GET",
        });
        wx.navigateTo({
          url: `/pages/paymethod/paymethod?price=${num.data.payPrice}&payOrderId=${num.data.payOrderId}&id=${num.data.id}`,
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: "error",
        });
      }
    } else {
      wx.showToast({
        title: "请选择结算套餐",
        icon: "none",
      });
    }
  },
  async subjectalreadyList(event) {
    const id = event.currentTarget.dataset.item.id;
    const itemID = event.currentTarget.dataset.item.itemId;
    const itemidList = this.data.alreadyList[itemID]
      .filter((item) => item.id)
      .map((item) => {
        return item.id;
      });
    const res = await request({
      url: app.globalData.baseURL + "/app-api/package/cart/create",
      method: "POST",
      data: {
        id: id,
        mainItem: false,
        itemId: itemidList,
        years: 0,
        selected: true,
      },
    });
  },
  async onChangeStepper(event) {
    const res = await request({
      url: app.globalData.baseURL + "/app-api/package/cart/update",
      method: "PUT",
      data: {
        id: event.currentTarget.dataset.item.id,
        years: event.detail,
        selected: true,
      },
    });
    this.getOrderList()
    this.setData({
      result:[],
      allPrice:0
    })
  },
  async addFunction(event) {
    const id = event.currentTarget.dataset.item.itemId;
    const arry1 = event.currentTarget.dataset.item.children;
    this.setData({
      [`productStatusMap.${id}`]: !this.data.productStatusMap[id],
    });
    const res = await request({
      url:
        app.globalData.baseURL +
        `/app-api/package/package-function/selectlist?packageId=${id}`,
      method: "GET",
    });
    const list = res.data;
    let idsInArray1 = new Set(arry1.map((item) => item.itemId));
    let idsInArray2 = list.filter((item) => !idsInArray1.has(item.functionId));
    if (res.data.length !== 0) {
      this.setData({
        addShow: true,
      });
    } else if (res.data.length == 0) {
      wx.showToast({
        title: "套餐版本较高无可选购功能",
        icon: "none",
      });
      this.setData({
        [`productStatusMap.${id}`]: null,
      });
    }
    this.setData({
      [`addList.${id}`]: idsInArray2,
    });
  },
  async addPakege(event) {
    const cartID = event.currentTarget.dataset.item.cartId;
    const id = event.currentTarget.dataset.param.functionId;
    const res = await request({
      url: app.globalData.baseURL + "/app-api/package/cart/create",
      method: "POST",
      data: {
        cartId: cartID,
        mainItem: false,
        itemId: id,
        years: 1,
      },
    });
    if (res.code == 0) {
      this.getOrderList();
      wx.showToast({
        title: "添加成功",
      });
      this.setData({
        result:[],
        allPrice:0
      })
    } else {
      wx.showToast({
        title: res.msg,
        icon: "none",
      });
    }
  },
  async deletePakege(event) {
    const id = event.currentTarget.dataset.item.id;
    const itemId = event.currentTarget.dataset.param.itemId;
    const res = await request({
      url: app.globalData.baseURL + `/app-api/package/cart/delete?id=${id}`,
      method: "DELETE",
    });
    if (res.code == 0) {
      this.getOrderList();
      wx.showToast({
        title: "删除成功",
        icon: "success",
      });
      this.setData({
        result:[],
        allPrice:0
      })
    } else {
      wx.showToast({
        title: res.msg,
        icon: "none",
      });
    }
  },
  async lookid(id) {
    const res = await request({
      url:
        app.globalData.baseURL +
        `/app-api/package/package-function/selectlist?packageId=${id}`,
      method: "GET",
    });
    const list = res.data;
    const arry1 = productStatusMap[id];
    let idsInArray1 = new Set(arry1.map((item) => item.itemId));
    let idsInArray2 = list.filter((item) => !idsInArray1.has(item.functionId));
    this.setData({
      [`addList.${id}`]: idsInArray2,
    });
  },
  // }
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getOrderList();
    this.setData({
      productList: [],
      result: [],
      allPrice: "0",
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.setData({
      productList: [],
      result: [],
      allPrice: "0",
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    return {
      title: "嘉之勤官网小程序",
      path: "/pages/index/index",
      imageUrl:
        "https://youyougo2.oss-cn-chengdu.aliyuncs.com/0201506f6fc0f4145e34159c2e2ac66b94b96450dd29e5a19d177edc5dad8023.png",
    };
  },
});
